//app.js
const constant = require('constant');
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 初次启动清除缓存token
    wx.clearStorageSync('token');

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              console.log('[app.js] 用户已进行过授权, set userInfo to '+res.userInfo );

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              //this.reg_wxinfo();
              //console.log('[app.js] getSetting: token='+this.globalData.token);
            }
          })
        } else {
          console.log("用户未授权");
          wx.showToast({
            title: '请稍后', icon: 'none', duration: 1000, success() {
              setTimeout(function () {
                wx.navigateTo({
                  url: '../auth/auth'
                })
              }, 1000)
            },
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    isLogin: false
  },
  //post请求
  $post(request_url, data, fun) {
    wx.showLoading({title: '加载中',mask: true});
    data.token = wx.getStorageSync("token");
    wx.request({
      url: constant.config.url_request + request_url,
      data: data,
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success (res) {
        if (res.code == 200){
          fun && fun(res.data);
        } else if (res.code == 401){
          wx.showToast({
            title: res.message, icon: 'none', duration: 500, success() {
              setTimeout(function () {
                wx.navigateTo({
                  url: '../login/login'
                })
              }, 500)
            },
          })
        }else{
          wx.showToast({title: res.message, icon: 'none', duration: 1000, },)
      }
        wx.hideLoading();
      }
    })
  },
  //get请求
  get(url_if, data, fun) {
    //console.log("[app.js] get request, url=" + url_if);
    wx.showLoading({ title: '加载中', mask: true });
    data.token = wx.getStorageSync("token");
    let that = this;
    wx.request({
      url: constant.config.url_request + url_if,
      data: data,
      success(res) {
        res = res.data;
        if (res.code == 200) {
          fun && fun(res);
        } else if (res.code == 401) {
          wx.showToast({
            title: res.message, icon: 'none', duration: 500, success() {
              setTimeout(function () {
                wx.navigateTo({
                  url: '../login/login?type=login'
                })
              }, 500)
            },
          })
        } else {
          wx.showToast({ title: res.message, icon: 'none', duration: 1000, })
        }
        wx.hideLoading();
      }
    })
  },
  reg_wxinfo() {
    let that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log('[app.js] reg_wxinfo: code=' + res.code);
        that.get('User/regwxinfo', {
          code: res.code,
          nickname: that.globalData.userInfo.nickName,
          sex: that.globalData.userInfo.gender,
          province: that.globalData.userInfo.province,
          city: that.globalData.userInfo.city,
          img: that.globalData.userInfo.avatarUrl
        }, function (res) {
          // if (res.code == 200 && res.data != null) {
          //   wx.setStorageSync("token", res.data.token)
          //   console.log('[app.js] reg_wxinfo success, set token to: ' + res.data.token);
          // }
          console.log('[app.js] reg_wxinfo: success' );
        })
      }
    })
    
  },
  checkLoginstatus() {
    if (this.globalData.isLogin == false) {
      wx.login({
        success: res => {
          this.get('User/isRegisted', {
            wx_code: res.code
          }, function (res) {
            if (res.data.openid == false) {
              wx.navigateTo({
                url: '../auth/auth',
              })
            } else if (res.data.openid == true) {
              var type = 'reg';
              if (res.data.phone == true) {
                type = 'login';
              }
              wx.navigateTo({
                url: '../login/login?type=' + type
              })
              // wx.showToast({
              //   title: '请稍后', icon: 'none', duration: 500, success() {
              //     setTimeout(function () {
              //       wx.navigateTo({
              //         url: '../login/login?type=' + type
              //       })
              //     }, 500)
              //   },
              // })
            } else {
              wx.showToast({
                title: '查询异常', icon: 'none', duration: 500, success() {
                  setTimeout(function () {
                    wx.navigateTo({
                      url: '../index/index'
                    })
                  }, 500)
                },
              })
            }
          })
        }
      })
    }
  }
})